<?php
class DocumentIndexController   extends Zone_Action{
	public function Fields($default=NULL){
		$data = array(
			type 	=> array(
				type 		=> 'INT',
				
				form_label	=> 'Loại tài liệu',			
			),
			title 	=> array(
				type 		=> 'INT',
				no_empty 	=>true,
				form_label	=> 'Tiêu đề',
			),
			content	=>array(
				type		=>'HTML',
				form_label	=>'Mô tả tài liệu'
			),
			pub =>array(
				type		=>'CHAR',
				form_label 	=>'Public'
			),
			date_updated =>array(
				type			=>'DATETIME',
				form_label 		=>'Ngày giờ chỉnh sửa',
				default_value	=>date("Y-m-d H:i:s")
			),
			updated_by_id =>array(
				type			=>'INT',
				form_label		=>'Chỉnh sửa',
				default_value	=>get_user_id()
			)
		);
		/* Neu chinh sua thi cac thong so duoc mac dinh trc */
		if( is_array( $default ) ){
			foreach( $data as $k => $config ){
				if( $config['type'] != 'NONE' && isset( $default[$k] ) ){
					$data[$k]['default_value'] = $default[$k];
				}
			}
		}	
		return $data;	
	}
	public function depAction(){
		$this->removeLayout();
		$dep = $this->getDepartments(0);
		$this->setContent($dep);
	}
	
	
	function zipDownload($file_names,$archive_file_name,$file_path){
		
		  $zip = new ZipArchive();
		 
		  if ($zip->open("files/tmp/".$archive_file_name, ZIPARCHIVE::CREATE )!==TRUE) {
				return $this->setJSON(array(
					alert => error("Không thể mở file.")
				));
		  }
		  
		  foreach($file_names as $files)
		  {
			$zip->addFile($file_path.$files,$files);
		  }
		  $zip->close();
		  header("Content-type: application/zip");
		  header("Content-Disposition: attachment; filename=$archive_file_name");
		  header("Pragma: no-cache");
		  header("Expires: 0");
		  readfile("files/tmp/$archive_file_name");
		  exit;
	}
	
	public function downloadAction(){
		$id = getInt("ID",0);
		$doc_name = $this->Model->fetchOne("SELECT title FROM `documents` WHERE `ID`='$id'");
		$files = $this->Model->fetchAll("SELECT * FROM `documents_files` WHERE `document_id`='$id'");
		$file_names = array();
		foreach($files as $file){
			$file_names[]=$file["filename"];
		}
		$archive_file_name = $doc_name.'.zip';
		
		$file_path="files/document/";
		$this->zipDownload($file_names,$archive_file_name,$file_path);
	}
	
	function insertDocumentUser($document_id,$arrToSend,$is_implement=null,$is_guest=null){
		for($i=0;$i<count($arrToSend);$i++){
			$data = array(
				"document_id"	=>$document_id,
				"user_id"		=>$arrToSend[$i]
			);
			$this->Model->insert("documents_users",$data);
		}
	}
	
	public function FolderFields($default=NULL){
		$data = array(
			title => array(
				type => 'TEXT',
				no_empty => true,
				form_label => 'Tên thư mục',
				min_length	=> 4,
				max_length	=> 30,
			),
			create_by_id => array(
				type 			=> 'NONE',
				default_value	=>	get_user_id()
			),
			desc => array(
				type => 'TEXT',
				form_label => 'Mô tả',
			)
		);
		/* Neu chinh sua thi cac thong so duoc mac dinh trc */
		if( is_array( $default ) ){
			foreach( $data as $k => $config ){
				if( $config['type'] != 'NONE' && isset( $default[$k] ) ){
					$data[$k]['default_value'] = $default[$k];
				}
			}
		}	
		return $data;	
	}
	
	public function initAction(){
		
		$user_id = get_user_id();
		$this->set('users',$this->Model->fetchRow("SELECT * FROM `users` WHERE `ID`='$user_id'"));
		$sqlDocumentType="SELECT * FROM `documents_types`";
		$arDocumentType=$this->Model->fetchAll($sqlDocumentType);
		$this->set('documentType',$arDocumentType);
		$arType = $this->getDocumentType();
		
		$this->set('documentTypeLayout',$arType);
		$this->view->listDiplomaSide = $this->getMyFolder();
		$this->view->departments = $this->Model->fetchAll("select * FROM `departments`");
		if(!$this->hasRole("document")){
			return $this->setContent(error("Bạn không có quyền truy cập phân hệ này."));
		}
	}
	
	function getMyFolder(){
		$id=get_user_id();
		$sql="select * FROM `documents_folder` WHERE `create_by_id`='$id'";
		$arr = $this->Model->fetchAll($sql);
		return $arr;
	}
	
	function getDocumentType(){
		$arrType = $this->Model->fetchAll("select * FROM `documents_types` ");
		return $arrType;
	}
	function countDocument($id){
		$sql="select COUNT(*) FROM `documents` as `a`
			LEFT JOIN `documents_users` as `b` ON `b`.`document_id`=`a`.`ID`
			LEFT JOIN `users` as `c` ON `c`.`ID`=`b`.`user_id`
		 WHERE `a`.`type`='$id' and `a`.`is_draft`='no' group by `a`.`ID`";
		return $this->Model->fetchOne($sql);
	}
	/*Index Action*/
	public function indexAction(){
		$type= getInt("type_id",0);
		$user_id = get_user_id();
		
		$vars = array();
		$WHERE = array();
		$order_by = " ORDER BY `a`.`title` DESC";
		
		$current_page = max(getInt('p',1),1);		
		$range_page = max(10,(int)$this->getConfig('user.page',20));
		
		if( isset($_REQUEST['p']) ){
			$vars['p'] = $current_page;
		}
		
		$limit = "LIMIT ".($current_page-1)*$range_page.",$range_page";
				
		$field_order = array('title','date_created','created_by_id','filename');
		foreach( $field_order as $f ){
			if( get('order_by') == $f ){
				$order_by = "ORDER BY $f ". ( get('order_type') == 'desc' ? 'desc' : 'asc');
				$vars['order_by'] = $f;
				if( get('order_type') == 'desc' ){
					$vars['order_by']='desc';
				}
				break;	
			}	
		}		
		$condition="";
		if($type!=0){
				$condition = " AND `a`.`type`='$type'  ";
				$arrType = $this->Model->fetchRow("SELECT * FROM `documents_types` WHERE `ID`='$type'");
				$this->set('x_title',$arrType['title']);
				$vars['type_id'] = $type;
		}else{
			$this->set('x_title',"Tài liệu công ty");
		}
		$total = $this->Model->fetchOne("SELECT COUNT(*) as `total` 
				FROM `documents` as `a`
				WHERE `a`.`is_draft`='no' AND `a`.`pub`='yes' $condition");
	
		$posts = $this->Model->fetchAll("
			SELECT `a`.*,`b`.`username`,`c`.`filename`,`c`.`ID` as `file_id` 
			FROM `documents` as `a`
				LEFT JOIN  `users` as `b` on `b`.`ID`=`a`.`created_by_id`
				LEFT JOIN `documents_files` as `c` on `c`.`document_id`=`a`.`ID`
			WHERE  `a`.`is_draft`='no' AND `a`.`pub`='yes' $condition  GROUP BY `a`.`ID` $order_by $limit");
		
		$a = $vars;
		unset($a['p']);
		
		$page = page_ajax('#Document/Index?'.to_query_configs($a).'&p=', $total , $range_page, $current_page);	
			
		$this->set(array(
			user_id		=>get_user_id(),
			page		=> $page,
			total		=> $total,
			vars		=> $vars,
			documents	=> $posts
		));	
		
	}

	public function saveAction(){
		$this->removeLayout();
		$user_id = get_user_id();
		$document_id = getInt("ID",0);
		$folder = $this->Model->fetchAll("select * FROM `documents_folder` WHERE `create_by_id` = '$user_id'");
		$strHtml.="
		<div class='x-form-container'>
		<form method='post' onsubmit='return ajax_form(this)' action='".actionUrl($this)."'>
		<input type='hidden' name='document_id' value='".$document_id."'/>
		<table class='x-form' width='100%' cellpadding='4px'>
			<tr>
				<td class='x-form-label' style='text-align:left'>Chọn thư mục để lưu</td>
			</tr>";
		$strHtml.= "
			<tr>
				</td><select name='folder_id' class='x-select' style='width:170px'>"; 
		foreach ($folder as $k=>$v){
			$strHtml.="<option value=".$v['ID'].">".$v['title']."</option>";
		}
		$strHtml.="</select>
				</td></tr>";
		
		$strHtml.="<tr><td align='center'><input type='submit' value='Lưu' class='x-button x-save'/></td></tr></table></form></div>";
		$this->setContent($strHtml);
		if(isPost()){
			$folder_id = $_POST['folder_id'];
			$document_id = $_POST['document_id'];
			if(isset($document_id)){
				$arrDocument = array(
					"document_id"	=>$document_id,
					"folder_id"		=>$folder_id
				);
				$check = $this->Model->insert("documents_folder_rep",$arrDocument);
			}
			if($check){
				return $this->setJSON(array(
					redirect => "#Document?folder_id=$folder_id"
				));
			}			
		}
	}
	//upload
	public function uploadAction(){
		$this->removeLayout();
		$document_id = getInt("ID",0);
		$user_id = get_user_id();
		if( isPost()){
			loadClass("ZData");
			$f = new ZData();
			$f->addField(array(
				file => array(
					type 		=> 'FILE',
					path		=> 'files/document/',
					no_empty	=> true
				)
			));
			
			$data = $f->getData();
			if( is_array( $data ) ){
				$file = $data['file'];
				$this->Model->insert("documents_files",array(
					document_id		=> $document_id,
					name			=> $file[0],
					type			=> $file[1],
					size			=> $file[2],
					filename		=> $file[3]
				));
				
				$file_id = $this->Model->lastId();				
				return $this->setJSON(array(
					content	=> "<div class='x-file-info'><input checked type='checkbox' name='files[]' value='$file_id'/>
								<a href='".ctrUrl($this)."/File?ID=$file_id' target='_blank'>{$file[3]} {$file[2]} KB	</a>
								</div>"
				));
			}else{
				return $this->setJSON(array(
					alert => error($data)
				));				
			}
			
		}	
		
	}
	
	public function addAction(){
		if(!$this->hasRole("document")){
			return $this->setContent(error("Bạn không có quyền tạo tài liệu"));
		}
		$user_id = get_user_id();
		$post = $this->Model->fetchRow("SELECT * FROM `documents` WHERE `created_by_id`='$user_id' AND `is_draft`='yes' LIMIT 1");
		if($post && $post['pub']=='yes'){
			$document_id = $post['ID'];
			$files = $this->Model->fetchAll("SELECT * FROM `documents_files` where `document_id`='$document_id'");
		}else{
			$this->Model->insert("documents",array(
				is_draft		=> 'yes',
				pub				=> 'yes',
				created_by_id	=> $user_id			
			));
			$post 	 = array();
			$files   = array();
			$document_id = $this->Model->lastId();
		}
		$this->set(array(
			post		=> 	$post,
			document_id =>	$document_id,
			files		=> 	$files			
		));
		if(isPost()){
			loadClass("ZData");
			$document_id = $_POST["ID"];
			$form = new ZData();
			$form->addFields( $this->Fields($post));
			$data = $form->getData();
			if( is_array($data)){
				
				$data['created_by_id'] = get_user_id();
				$data['date_created']  = date("Y-m-d H:i:s");
				$data['is_draft']='no';
				$data['pub']='yes';
				
				$check = $this->Model->update("documents",$data,"`ID`='$document_id'");
				
				$this->insertDocumentUser($document_id,array($user_id));
				//xoa file khong check
				$files_selected = (array)$_POST['files'];
				$files = $this->Model->fetchAll("SELECT * FROM `documents_files` WHERE `document_id`='$document_id'");
				foreach( $files as $f ){
					if( !in_array( $f['ID'], $files_selected ) ){
						$this->Model->delete("documents_files","`ID`='{$f['ID']}'");
						@unlink("files/document/{$f['name']}");
					}
				}
				
				$files_selected = (array)$_POST['files'];
				$files = $this->Model->fetchAll("SELECT * FROM `documents_files` WHERE `document_id`=$document_id");
				foreach( $files as $f ){
					if( !in_array( $f['ID'], $files_selected ) ){
						$this->Model->delete("documents_files","`ID`='{$f['ID']}'");
						@unlink("files/document/{$f['name']}");
					}
				}
				
				return $this->setJSON(array(
					redirect	=> "#Document?public=1"
				));
			}else{
				return $this->setJSON(array(
					message => error($data)
				));
			}			
		}
		
	}
	
	public function editAction(){
		$document_id = getInt("ID",0);
		$user_id = get_user_id();
		//
		$sqlCheckRol = "select * from `documents` where `ID`='$document_id'";
		$arCheckRol = $this->Model->fetchRow($sqlCheckRol);
		if($arCheckRol['created_by_id']!=$user_id){
			$this->setContent(error("Bạn không có quyền chỉnh sửa tài liệu này"."<u><a href='#Document?public=1' style='margin-left:15px;'>Quay lại danh sách<< </a></u>"));
		}
		//
		$post = $this->Model->fetchRow("SELECT `a`.* FROM `documents` as `a`
			LEFT JOIN `documents_users` as `b` ON `a`.`ID`=`b`.`document_id`
			 WHERE `a`.`ID`='$document_id'");
		if(!$post){
			return $this->setJSON(array(
				message	=> error('Tài liệu không tồn tại hoặc đã bị xóa trước đó.')
			));
		}
		$files = $this->Model->fetchAll("SELECT * FROM `documents_files` WHERE `document_id`='$document_id'");
	
		$this->set(array(
			post		=> $post,
			files		=> $files,
		));
		
		if(isPost()){
			loadClass("ZData");
			$form = new ZData();
			$form->addFields( $this->Fields($post));
			$data = $form->getData();
			if( is_array($data)){
				$data['is_draft']='no';
				$check = $this->Model->update("documents",$data,"`ID`='$document_id'");
				
				$this->insertDocumentUser($document_id,array($user_id));
				
				$files_selected = (array)$_POST['files'];
				$files = $this->Model->fetchAll("SELECT * FROM `documents_files` WHERE `document_id`=$document_id");
				foreach( $files as $f ){
					if( !in_array( $f['ID'], $files_selected ) ){
						$this->Model->delete("documents_files","`ID`='{$f['ID']}'");
						@unlink("files/document/{$f['name']}");
					}
				}
				return $this->setJSON(array(
					redirect	=> "#Document?public=1"
				));
			}else{
				return $this->setJSON(array(
					message => error($data)
				));
			}			
		}
	}
	
	
public function addfolderAction(){
		$this->removeLayout(); 
		$table.='
		<div class="x-form-container">
		<form action="'.actionUrl($this).'" method="post" onsubmit="return ajax_form(this)">
		<div class="form-message"></div>
		<table  cellpadding="4px" class="x-form">
			<tr>
				<td width="100" class="x-form-label" w>Tên folder :</td>
				<td><input style="width:287px" type="text" name="title" class="x-text" /></td>
			</tr>
			<tr>
				<td width="100" class="x-form-label">Mô tả :</td>
				<td>
					<textarea style="width:290px" class="x-text" name="desc"></textarea>
				</td>
			</tr>
			<tr>
				<td colspan="4" align="center">
					<input type="submit" value="Tạo mới" class="x-button x-save"/>
					
				</td>
			</tr>
		</table>
		</form>
		</div>
		';
		$this->setContent($table);
		if(isPost()){
			loadClass("ZData");
			$form = new ZData();
			$form->addFields($this->FolderFields());
			$data = $form->getData();
			if( is_array($data)){
				$check = $this->Model->insert("documents_folder",$data);
				if(!$check){
					return $this->setJSON(array(
						message	=> error('Không thêm được thư mục')
					));
				}
				return $this->setJSON(array(
					redirect	=> "#Document"
				));
			}else{
				return $this->setJSON(array(
					message	=> error($data)
				));
			}
		}
	}
	public function editfolderAction(){
		$this->removeLayout();
		$id = getInt('ID',0);
		$crFolder = $this->Model->fetchRow("SELECT * FROM `documents_folder` WHERE ID='$id'"); 
		$table.='
		<div class="x-form-container">
		<form action="'.actionUrl($this).'" method="post" onsubmit="return ajax_form(this)">
		<input type="hidden" value="'.$id.'" name="folder_id" />
		<div class="form-message"></div>
		<table width="365px" cellpadding="4px" class="x-form">
			<tr>
				<td><b>Tên folder</b></td>
			</tr>
			<tr>
				<td><input style="width:320px;" value="'.$crFolder['title'].'" type="text" name="title" class="x-text" /></td>
			</tr>
			<tr>
				<td><b>Mô tả</b></td>
			</tr>
			<tr>
				<td>
					<textarea style="width:320px;"  class="x-text" name="desc">'.$crFolder['desc'].'</textarea>
				</td>
			</tr>
			<tr>
				<td colspan="2" align="right">
					<input type="submit" value="Sửa" class="x-button x-save"/>
					
				</td>
			</tr>
		</table>
		</form>
		</div>
		';
		$this->setContent($table);
		if(isPost()){
			$folder_id = $_POST['folder_id'];
			loadClass("ZData");
			$form = new ZData();
			$form->addFields($this->FolderFields($crFolder));
			$data = $form->getData();
			if( is_array($data)){
				$check = $this->Model->update("documents_folder",$data," `ID`='$folder_id' ");
				if(!$check){
					return $this->setJSON(array(
						message	=> error('Không sửa được thư mục')
					));
				}
				return $this->setJSON(array(
					redirect	=> "#Document"
				));
			}else{
				return $this->setJSON(array(
					message	=> error($data)
				));
			}
		}
	}
	
	public function viewAction(){
		$id=getInt('ID',0);
		$chk = $this->Model->fetchRow("SELECT * FROM `documents` WHERE `ID`='$id'");
		if($chk['title']==""){
			return $this->setJSON(array(
				alert =>error("Bản ghi không tồn tại hoặc đã bị xóa trươc đó")
			));
		}
		$arCrDoc  = $this->Model->fetchRow("
		SELECT `a`.*,`b`.`title` as `document_type`,`c`.`username`,c.`username` as `updated_by_name`,`c`.`is_deleted` as `created_is_deleted`
		FROM `documents` as `a` 
			LEFT JOIN `documents_types` as `b` ON `b`.`ID`=`a`.`type`
			LEFT JOIN `users` as `c` ON `c`.`ID`=`a`.`created_by_id`
		WHERE `a`.`ID`='$id'");
		$topRight = $this->Model->fetchRow("
			SELECT `a`.`updated_by_id`,`a`.`date_updated`,`b`.`username` as `updated_by_name`
			FROM `documents` as `a`
			LEFT JOIN `users` as `b` ON `a`.`updated_by_id`=`b`.`ID`
			WHERE `a`.`ID`='$id'
		");
		$file = $this->Model->fetchAll("SELECT * FROM `documents_files` WHERE `document_id`='$id'");
		if($arCrDoc["pub"]=="yes"){
			$is_forward = 1;
		}else{
			$is_forward=0;
		}
		$this->set(array(
            is_forward       	=>$is_forward,
            crDocument      	=>$arCrDoc,
			files 				=>$file,
			cr_update			=>$topRight
        ));
	}	
	
	public function deleteAction(){
		$id=getInt("ID",0);
		$user_id=get_user_id();
		if($id!=0){
			$check = $this->Model->fetchRow("SELECT * FROM `documents` WHERE `ID`='$id'");
			$files = $this->Model->fetchAll("SELECT * FROM `documents_files` WHERE `document_id`='$id'");
			
			if($check['created_by_id']!=get_user_id()){
				return $this->setJSON(array(
					alert =>error('Bạn không có quyền xóa tài liệu này')
				));
			}else{
				foreach( $files as $f ){
						$this->Model->delete("documents_files","`ID`='{$f['ID']}'");
						@unlink("files/document/{$f['name']}");
				}
				$this->Model->delete("documents"," `ID`='$id' ");
			}
		}else{
			$id = $_POST["checkbox_diploma"];
			if(empty($id)===true){
				return $this->setJSON(array(
					alert =>error('Chưa có tài liệu nào được chọn.')
				));
			}
			for($i=0;$i<count($id);$i++){
				$k = $id[$i];
				$files = $this->Model->fetchAll("SELECT * FROM `documents_files` WHERE `document_id`='$k'");
				foreach( $files as $f ){
						@unlink("files/document/{$f['name']}");
				}
			}
			$strID = "(".join(",",$id).")";
			$this->Model->delete("documents","`ID` in $strID AND `created_by_id`='$user_id'");
			
		}
		return $this->setJSON(array(
			redirect	=> "#Document/"
		));
	}
	
	public function deletefolderAction(){
		$folder_id = getInt("ID",0);
		$check = $this->Model->delete("documents_folder","`ID`='$folder_id'");
		return $this->setJSON(array(
			redirect => "#Document/Index/Index"
		));
	}
	/*get deparment*/
	protected function getDepartments( $id, $depth = 0, $SELECTed='', $name='users' ){
		//Lay phong ban con
		$sub_departments 
			= $this->Model->fetchAll("SELECT `a`.*,IF(`b`.`ID`,`b`.`ID`,0) as `parentID` 
				FROM `departments` as `a` 
				LEFT JOIN `departments` as `b` ON 
				`a`.`parent_id`=`b`.`ID` HAVING `parentID`='$id'");
		$staffs = $this->Model->fetchAll("select *,IF( '$SELECTed' LIKE CONCAT('%,',`ID`,'%') , ' checked', '' ) as 
        `checked`  FROM `users` WHERE `department_id`='$id'");

		if(count($staffs) == 0 && count($sub_departments) == 0){
			return '';
		}	
			
		//class
		$class = $depth == 0 ? "tree-list tree-root":"tree-list";
			
		$list = "<div class='tree-list-outer'>
			<div class=\"$class\">";
		foreach( $sub_departments as $k => $sub ){
			$subs = $this->getDepartments( $sub['ID'], $depth+1, $SELECTed );
			
			$cl = $subs !="" ? "" : " tree-link-empty";
			$cls = $subs !="" ? "" : " tree-folder-empty";
			
			//show child in depth
			$has_sub  = $this->Model->fetchOne("select * FROM `departments` WHERE `parent_id`='{$sub['ID']}'");
			$is_close = $has_sub ? "" : " tree-section-close";
			
			$list .="<div class='tree-folder-outer'>
				<a class='tree-node' onclick='tree_collapse(this)'></a>
				<div class='tree-folder'>
					<a class='tree-title'><input type='checkbox' class='tree-check' onclick='tree_check_all(this)'/>{$sub['title']}</a>
					$subs
				</div></div>";
		}
		
		foreach( $staffs as $k => $staff ){
			$list .="<a class='tree-item-outer'>
				<span class='tree-item'><span class='tree-item-icon'></span>
				<input type='checkbox' name='nametoforward[]' value='{$staff['ID']}'{$staff['checked']}' class='tree-check'/>".$staff['username']."</span>
				</a>";					
		}
		$list .="</div></div>";
		return $list;
	}
	public function fileAction(){
		$this->removeLayout();
		$file_id = get('ID',0);
		$file = $this
			->Model->fetchRow("SELECT * FROM `documents_files` as `a` WHERE `a`.`ID`='$file_id' LIMIT 1");
		
		if( !$file['filename'] ){
			return $this->setContent(error('File đã bị xóa hoặc không tồn tại'));
		}
		$file_path = "files/document/{$file['name']}";
		if( !file_exists( $file_path ) ){
			return $this->setError('404');
		}	
		if( get('type') == 'icon' ){	
			$img_types = array('image/gif','image/png','image/x-png','image/jpeg','image/x-jpeg','image/jpg');
			if( in_array($file['type'],$img_types) ){
				loadClass('PHPThumb');
				$thumb = PhpThumbFactory::create($file_path);
				$thumb->resize(60, 60);
				$thumb->show();
			}else{
				@readfile("files/static/icon.gif");	
			}		
		}else if( get('type') == 'view' ){	
			$img_types = array('image/gif','image/png','image/x-png','image/jpeg','image/x-jpeg','image/jpg');
			if( in_array($file['type'],$img_types) ){
				loadClass('PHPThumb');
				$thumb = PhpThumbFactory::create($file_path);
				$thumb->show();
			}else{
				@readfile("files/static/icon.gif");	
			}		
		}else{
			@header("Content-Disposition: attachment; filename={$file['name']}");
			@readfile($file_path);
		}
	}
	
	function sendMessage($user_id, $content,$title,$url){
 		for($i=0;$i<count($user_id);$i++){
			$this->Model->insert("notices",array(
				created_by_id   => get_user_id(),
				user_id			=> $user_id[$i],
				title			=> $title,
				url				=> $url,
				content			=> $content,
				date			=> mysql_date()
			));
 		}
	}
 	
}
?>